package com.heima.netty.eventloop;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

/**
 * @author ZhengDp
 * @Date 2023/6/24 19:16
 */
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        // 创建独立的EventLoopGroup --> 将消息的处理逻辑 分离出来，给另外的Group进行处理（线程）
        EventLoopGroup group = new DefaultEventLoop();
        new ServerBootstrap()

                .group(new NioEventLoopGroup(1),new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handle1",new ChannelInboundHandlerAdapter() {
                            @Override                                           // ByteBuf
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buffer = (ByteBuf) msg;
                                log.info(buffer.toString(Charset.defaultCharset()));
                                // 将消息传递到下一个 handler中 --> 责任链
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(group,"handle2",new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info(buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                })
                .bind(7777);
    }
}
